import { BeforeInsert, BeforeUpdate, BeforeRemove, PrimaryGeneratedColumn, Column } from 'typeorm';
import { IsOptional, IsInt, Min } from 'class-validator';
import { Field, Int, ObjectType } from 'type-graphql';

@ObjectType()
export class DBEntity {
  @PrimaryGeneratedColumn({
    type: 'bigint',
    name: 'id',
  })
  @IsOptional()
  @IsInt()
  @Min(1)
  @Field(type => Int, { description: '主键id' })
  id: number;

  @Column('datetime', {
    nullable: false,
    default: () => 'CURRENT_TIMESTAMP',
    name: 'gmt_create',
    comment: '创建时间',
  })
  @Field({ description: '记录创建时间' })
  gmtCreate: Date;

  @Column('datetime', {
    nullable: false,
    default: () => 'CURRENT_TIMESTAMP',
    name: 'gmt_modified',
    comment: '修改时间',
  })
  @Field({ description: '记录最后更新时间' })
  gmtModified: Date;

  @BeforeInsert()
  beforeInsert() {
    this.id = null;
  }

  @BeforeUpdate()
  beforeUpdate() {
    if (!this.id || this.id < 1) {
      throw new Error('无效的update id');
    }
  }

  @BeforeRemove()
  beforeRemove() {
    if (!this.id || this.id < 1) {
      throw new Error('无效的delete id');
    }
  }
}
